package com.cxcs.cxcsojbackendquestionservice.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxcs.cxcsojbackendcommon.common.DeleteRequest;
import com.cxcs.cxcsojbackendcommon.common.ErrorCode;
import com.cxcs.cxcsojbackendcommon.constant.CommonConstant;
import com.cxcs.cxcsojbackendcommon.exception.BusinessException;
import com.cxcs.cxcsojbackendcommon.utils.SqlUtils;
import com.cxcs.cxcsojbackendmodel.dto.questionsubmit.QuestionSubmitAddRequest;
import com.cxcs.cxcsojbackendmodel.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.cxcs.cxcsojbackendmodel.entity.Question;
import com.cxcs.cxcsojbackendmodel.entity.QuestionSubmit;
import com.cxcs.cxcsojbackendmodel.entity.User;
import com.cxcs.cxcsojbackendmodel.enums.QuestionSubmitLanguageEnum;
import com.cxcs.cxcsojbackendmodel.enums.QuestionSubmitStatusEnum;
import com.cxcs.cxcsojbackendmodel.vo.QuestionSubmitVO;
import com.cxcs.cxcsojbackendmodel.vo.QuestionVO;
import com.cxcs.cxcsojbackendmodel.vo.UserVO;
import com.cxcs.cxcsojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.cxcs.cxcsojbackendquestionservice.rabbitmq.MyMessageProducer;
import com.cxcs.cxcsojbackendquestionservice.service.QuestionService;
import com.cxcs.cxcsojbackendquestionservice.service.QuestionSubmitService;
import com.cxcs.cxcsojbackendserviceclient.service.JudgeFeignClient;
import com.cxcs.cxcsojbackendserviceclient.service.UserFeignClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 题目提交服务实现
 *
 * @author CxCS
 * @Version: 1.0
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {
    @Resource
    private QuestionService questionService;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private MyMessageProducer myMessageProducer;

    @Resource
    @Lazy
    private JudgeFeignClient judgeService;

    /**
     * 题目提交
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return  提交记录的id
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已题目提交
        long userId = loginUser.getId();

        // 校验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }

        // 每个用户串行题目提交
        /*
            加锁，防止用户多次重复提交
            锁必须要包裹住事务方法
         */
//        QuestionSubmitService questionSubmitService = (QuestionSubmitService) AopContext.currentProxy();
//        synchronized (String.valueOf(userId).intern()) {
//            return questionSubmitService.doQuestionSubmitInner(userId, questionId);
//        }

        // 先直接进行添加操作
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(userId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        // todo 设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());  // 默认等待中
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if(!save) {
            // 提交失败
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据输入失败");
        }

        // todo 异步执行 判题服务 [消息队列RabbitMQ]
        Long questionSubmitId = questionSubmit.getId();
        // 消息队列生产者设置 交换机 队列key 题目提交id
        myMessageProducer.sendMessage("code_exchange", "my_routingKey", String.valueOf(questionSubmitId));

        // 原 异步化调用判题服务
//        CompletableFuture.runAsync(() -> {
//            judgeService.doJudge(questionSubmitId);
//        });

        return questionSubmitId;
    }


    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();

        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);  // 暂时不限定状态
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     *  获取单条信息封装类
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmit.getUserId() && !userFeignClient.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        UserVO userVO = userFeignClient.getUserVOById(questionSubmit.getUserId());

        //  封装题目信息
        Question question = questionService.getById(questionSubmitVO.getQuestionId());
        QuestionVO questionVO = QuestionVO.objToVo(question);
        questionSubmitVO.setQuestionVO(questionVO);

        if(userVO == null || questionVO == null) {
            return null;
        }

        // 封装用户信息
        UserVO respUserVO = new UserVO();
        respUserVO.setId(userId);
        respUserVO.setUserName(userVO.getUserName());
        questionSubmitVO.setUserVO(respUserVO);

        return questionSubmitVO;
    }


    /**
     *  获取多条信息封装类
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

    /**
     *  批量删除提交记录
     *
     * @param questionId
     * @return
     */
    @Override
    public Boolean removeQuestionSubmitByQuestionId(Long questionId) {
        QuestionSubmitQueryRequest questionSubmitQueryRequest = new QuestionSubmitQueryRequest();
        questionSubmitQueryRequest.setQuestionId(questionId); // 过滤条件 题目id
        // 封装
        QueryWrapper<QuestionSubmit> queryWrapper = this.getQueryWrapper(questionSubmitQueryRequest);

        boolean res = this.remove(queryWrapper);  // 删除

        return res;
    }


}




